# coding: utf-8

# -------------------------------------------------------------------------------
# Name:         bif_dict.py
# Description:
# Author:       XiangjunZhao
# EMAIL:        2419352654@qq.com
# Date:         2022/1/10 6:36 下午
# -------------------------------------------------------------------------------

def reserving_specified_fields(obj: [dict, list], expr: [str, list, dict]):
    """
    保留指定字段
    Args:
        obj:
        expr: 需要保留的字段，以英文逗号进行分隔；如果有:分隔，则冒号之前的为原字段，冒号之后的为替换字段

    Returns:

    """
    if isinstance(expr, str):
        expr = list(map(lambda x: x.strip(), expr.split(',')))
    if isinstance(expr, list):
        expr_dict = {}
        for index, expr_item in enumerate(expr):
            if isinstance(expr_item, str):
                expr_list = expr_item.split(':')
                if len(expr_list) == 1:
                    expr[index] = {expr_list[0].strip(): expr_list[0].strip()}
                elif len(expr_list) > 1:
                    expr[index] = {expr_list[0].strip(): expr_list[1].strip()}
                expr_dict.update(expr[index])
        expr = expr_dict
    if isinstance(obj, list):
        for index, obj_item in enumerate(obj):
            obj[index] = reserving_specified_fields(obj_item, expr)
        return obj
    elif isinstance(obj, dict) and isinstance(expr, dict):
        return {expr[k]: v for k, v in obj.items() if k in expr.keys()}


if __name__ == '__main__':
    data = [[{
        'name': 'name1',
        'age': 'age1',
        'age1': 'age1t'
    }], {
        'name': 'name1',
        'age': 'age1',
        'age1': 'age1t'
    }, {
        'name': 'name2',
        'age': 'age2'
    }, {
        'name': 'name1',
        'age': 'age1',
        'age1': 'age1t'
    }]
    print(reserving_specified_fields(data, 'name,age1:age'))
